<script setup>
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
import { yiYanService } from '@/api/tools'
const textArr = ref([])

const isDisabled = ref(false)
let timer = null
const loadText = async () => {
  showNotify({ type: 'primary', message: '每隔3秒加载一次随机一言' })
  timer = setInterval(async () => {
    try {
      const text = await yiYanService()
      textArr.value.push(text.data)
    } catch (err) {
      clearInterval(timer)
      showNotify({ type: 'primary', message: '加载失败' })
    }
  }, 3000)
  isDisabled.value = true
}

const stopLoad = () => {
  clearInterval(timer)
  showNotify({ type: 'primary', message: '已停止加载' })
  isDisabled.value = false
}

onMounted(async () => {
  // timer = setInterval(async () => {
  const text = await yiYanService()
  // console.log(text.data)
  textArr.value.push(text.data)
  // }, 3000)
})
onBeforeUnmount(() => {
  clearInterval(timer)
})
function copyToClipboard(text) {
  const input = document.createElement('input')
  input.setAttribute('value', text)
  document.body.appendChild(input)
  input.select()
  document.execCommand('copy')
  document.body.removeChild(input)
  showToast('已复制')
}
</script>

<template>
  <div class="tool-box-yiyan">
    <div class="tool-box-yiyan-header">
      <van-nav-bar
        fixed
        :placeholder="true"
        title="随机一言"
        left-arrow
        @click-left="router.go(-1)"
      />
    </div>
    <div class="tool-box-yiyan-content">
      <div class="tool-box-yiyan-text" v-for="item in textArr" :key="item">
        <van-button
          @click="copyToClipboard(item)"
          plain
          size="mini"
          type="primary"
          style="margin-right: 5px"
        >
          复制
        </van-button>
        <van-text-ellipsis
          rows="3"
          :content="item"
          expand-text="展开"
          collapse-text="收起"
        />
      </div>
      <div class="tool-box-yiyan-content-button">
        <van-button
          @click="loadText()"
          :disabled="isDisabled"
          plain
          size="small"
          type="primary"
        >
          加载文本
        </van-button>
        <van-button
          @click="stopLoad()"
          :disabled="!isDisabled"
          plain
          size="small"
          type="primary"
        >
          停止加载
        </van-button>
      </div>
    </div>
  </div>
</template>
<style scoped>
.tool-box-yiyan-content {
  width: 100%;
  margin-bottom: 100px;
}
.tool-box-yiyan-text {
  margin: 10px 20px;
  border: 0.5px solid #ccc;
}
.tool-box-yiyan-content-button {
  width: 90%;
  display: flex;
  justify-content: space-between;
  /* margin: 10px auto; */
  position: fixed;
  bottom: 30px;
  left: 18px;
}
</style>
